<script setup lang="ts">
import { ProjectForm, RandomProjectVo, ProjectSetting } from '@/api/exam/project/types';
import {
  AnswerSettingConfigs,
  ExamSettingConfigs,
  ExamSettingSwitchConfigs,
  SubmittedSettingConfigs
} from '@/views/exam/project/info/config';
import { listRepo, pickQuestion } from '@/api/exam/repo';
import { RepoVO } from '@/api/exam/repo/types';
import { generateRandomId, QUESTION_TYPE_CONFIG } from '@/views/exam/template/info/config';
import { PlusOutlined } from '@ant-design/icons-vue';

// 定义组件的 Props 接口，包含 projectForm 属性
interface Props {
  projectForm: any | ProjectForm;
}

// 定义组件 Props，并设置默认值
const props = withDefaults(defineProps<Props>(), {
  projectForm: {
    setting: {}
  }
});

// 将父组件传递的 projectForm 转换为响应式对象，并监听其变化
const projectForm = ref<ProjectForm>(props.projectForm);
watch(() => props.projectForm, () => {
  projectForm.value = props.projectForm; // 当父组件更新时同步更新本地引用
});

// 获取项目设置的初始值
const setting = ref<ProjectSetting>(projectForm.value.setting);

// 定义锚点容器的引用
const containerRef = ref();

// 定义锚点链接配置
const anchorLinks = [
  { href: '#answer-setting', title: '项目显示', icon: 'document' },
  { href: '#exam-setting', title: '考试设置', icon: 'document-setting' },
  { href: '#submitted-setting', title: '回收设置', icon: 'security' }
];

// 根据 ExamSettingConfigs 动态生成考试设置字段的开关状态
const examSettingFlags = reactive(
  Object.fromEntries(
    Object.keys(ExamSettingConfigs).map(field => [
      field,
      ExamSettingConfigs[field].hasValue(setting.value.examSetting[field]) // 判断字段是否有值
    ])
  ) as Record<any, boolean>
);
const submittedSettingFlags = reactive(
  Object.fromEntries(
    Object.keys(SubmittedSettingConfigs).map(field => [
      field,
      SubmittedSettingConfigs[field].hasValue(setting.value.submittedSetting[field]) // 判断字段是否有值
    ])
  ) as Record<any, boolean>
);
// 统一处理考试设置字段的开关逻辑
const handleFieldChange = (field: string, value: any | boolean) => {
  // 当开关关闭时，重置对应字段的值为默认值
  if (!value) {
    setting.value.examSetting[field] = ExamSettingConfigs[field].resetValue;
  }
};
const handleSubmittedFieldChange = (field: string, value: any | boolean) => {
  // 当开关关闭时，重置对应字段的值为默认值
  if (!value) {
    setting.value.submittedSetting[field] = SubmittedSettingConfigs[field].resetValue;
  }
};

// 随机题目设置相关逻辑
const randomProjectList = ref<RandomProjectVo[]>([]); // 存储随机题目的列表
const repoList = ref<RepoVO[]>([]); // 存储题库列表
const dialog = reactive<DialogOption>({
  visible: false, // 对话框是否可见
  title: '' // 对话框标题
});

// 打开随机题目设置对话框
const handleRandomProject = () => {
  if (projectForm.value.setting.examSetting.randomProject) {
    // 如果已有随机题目配置，则初始化 projectRepoList
    randomProjectList.value = projectForm.value.setting.examSetting.randomProject;
  }
  dialog.title = '随机题目'; // 设置对话框标题
  dialog.visible = true; // 显示对话框
};

// 获取题库列表
const getRepoList = async () => {
  const res = await listRepo(); // 调用 API 获取题库列表
  repoList.value = res.data; // 更新题库列表
};

const getTotalScore = () => {
  let totalScore = 0;
  randomProjectList.value.forEach((item) => {
    totalScore += item.score * item.num;
  });
  return totalScore;
};
const getTotalNum = () => {
  let totalNum = 0;
  randomProjectList.value.forEach((item) => {
    totalNum += item.num;
  });
  return totalNum;
};
// 添加一行随机题目配置
const addRow = () => {
  randomProjectList.value.push({
    id: generateRandomId(), // 生成唯一 ID
    repoId: '', // 关联题库 ID
    questionTypes: null, // 题型
    tags: [], // 标签
    num: null, // 题数
    score: null // 每题分数
  });
};

// 删除指定行的随机题目配置
const removeRow = (id: string) => {
  return new Promise<void>((resolve) => {
    randomProjectList.value = randomProjectList.value.filter(item => item.id !== id); // 过滤掉指定 ID 的行
    resolve(); // 解决 Promise
  });
};

// 重置随机题目配置
const reset = () => {
  randomProjectList.value = []; // 清空随机题目列表
};

// 提交随机题目配置或选择题目
const loading = ref(false); // 加载状态
const submit = async () => {
  loading.value = true; // 开启加载状态
  if (dialog.title === '随机题目') {
    // 如果是随机题目配置
    projectForm.value.setting.examSetting.randomProject = randomProjectList.value; // 更新项目设置
    loading.value = false; // 关闭加载状态
  } else {
    // 如果是选择题目
    const res = await pickQuestion(randomProjectList.value).finally(() => {
      loading.value = false; // 确保加载状态关闭
    });
    projectForm.value.survey.children.push(...res.data); // 更新问卷子项
    randomProjectList.value = []; // 清空随机题目列表
  }
  dialog.visible = false; // 关闭对话框
};

// 暴露 submit 方法供外部调用
defineExpose({
  submit
});

// 在组件挂载时获取题库列表
onMounted(async () => {
  await getRepoList();
});
</script>

<template>
  <el-main>
    <a-flex justify="space-between" style="height: 100%;">
      <div class="setting-nav">
        <el-anchor :container="containerRef" :select-scroll-top="true">
          <el-anchor-link
            v-for="link in anchorLinks"
            :key="link.href"
            :href="link.href"
          >
            <template #default>
              <div class="setting-nav-item">
                <a-flex align="center" vertical>
                  <svg-icon :icon-class="link.icon" class="nav-item-icon" />
                  <span>{{ link.title }}</span>
                </a-flex>
              </div>
            </template>
          </el-anchor-link>
        </el-anchor>
      </div>
      <div ref="containerRef" class="setting-content">
        <a-row :gutter="[16,16]">
          <a-col :span="24" id="answer-setting">
            <a-card class="setting-card">
              <template #title>
                <div class="setting-title">
                  <svg-icon icon-class="document" />
                  项目显示
                </div>
              </template>
              <div
                v-for="(item, field) in AnswerSettingConfigs"
                :key="field"
                class="setting-item setting-item-switch">
                <span>{{ item.label }}
                  <el-tooltip
                    v-if="item.tooltip" placement="top">
                    <template #content>
                      <div v-html="item.tooltip.content" />
                    </template>
                    <svg-icon icon-class="tip" />
                  </el-tooltip>
                </span>
                <a-switch v-model:checked="setting.answerSetting[field]"
                          checked-children="T" un-checked-children="F" />
              </div>
            </a-card>
          </a-col>
          <a-col :span="24" id="exam-setting">
            <a-card class="setting-card">
              <template #title>
                <div class="setting-title">
                  <svg-icon icon-class="document-setting" />
                  考试设置
                </div>
              </template>
              <div
                v-for="(item, field) in ExamSettingSwitchConfigs"
                :key="field"
                class="setting-item setting-item-switch">
                <span>{{ item.label }}
                  <el-tooltip
                    v-if="item.tooltip" placement="top">
                    <template #content>
                      <div v-html="item.tooltip.content" />
                    </template>
                    <svg-icon icon-class="tip" />
                  </el-tooltip>
                </span>
                <a-switch v-model:checked="setting.examSetting[field]"
                          checked-children="T" un-checked-children="F" />
              </div>
              <div v-for="(config, field) in ExamSettingConfigs" :key="field">
                <div class="setting-item">
                  <div class="setting-item-switch">
                    <span>{{ config.label }}
                      <el-tooltip v-if="config.tooltip" placement="top">
                        <template #content>
                          <div v-html="config.tooltip.content" />
                        </template>
                        <svg-icon icon-class="tip" />
                      </el-tooltip>
                    </span>
                    <!--随机题目配置-->
                    <a-flex justify="end" gap="small" align="center">
                      <div v-if="field==='randomProject' && examSettingFlags.randomProject ">
                        <a-button type="text" @click="handleRandomProject">设置</a-button>
                      </div>
                      <a-switch
                        v-model:checked="examSettingFlags[field]"
                        checked-children="T" un-checked-children="F"
                        @change="val => handleFieldChange(field, val)"
                      />
                    </a-flex>

                  </div>
                  <!-- 动态组件渲染 -->
                  <div v-if="examSettingFlags[field] && config.component">
                    <component
                      :is="config.component"
                      v-model="setting.examSetting[field]"
                      v-bind="config.props"
                    />
                  </div>
                </div>
              </div>

            </a-card>
          </a-col>
          <a-col :span="24" id="submitted-setting">
            <a-card class="setting-card">
              <template #title>
                <div class="setting-title">
                  <svg-icon icon-class="security" />
                  回收设置
                </div>
              </template>
              <div v-for="(config, field) in SubmittedSettingConfigs" :key="field">
                <div class="setting-item">
                  <div class="setting-item-switch">
                    <span>{{ config.label }}
                      <el-tooltip v-if="config.tooltip" placement="top">
                        <template #content>
                          <div v-html="config.tooltip.content" />
                        </template>
                        <svg-icon icon-class="tip" />
                      </el-tooltip>
                    </span>
                    <a-switch
                      v-model:checked="submittedSettingFlags[field]"
                      checked-children="T" un-checked-children="F"
                      @change="val => handleSubmittedFieldChange(field, val)"
                    />
                  </div>
                  <!-- 动态组件渲染 -->
                  <div v-if="submittedSettingFlags[field] && config.component">
                    <component
                      :is="config.component"
                      v-model="setting.submittedSetting[field]"
                      v-bind="config.props"
                    />
                  </div>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </a-flex>
  </el-main>

  <el-dialog v-model="dialog.visible" :append-to-body="true" :with-header="false" width="80%"
             class="project-dialog">
    <template #title>
      <a-flex gap="large">
        <span>总分: {{ getTotalNum() }}</span>
        <span>题数: {{ getTotalScore() }}</span>
      </a-flex>
    </template>
    <el-table :data="randomProjectList" height="350">
      <el-table-column label="关联题库" align="center" prop="repoId">
        <template #default="scope">
          <el-select v-model="scope.row.repoId">
            <el-option v-for="item in repoList" :key="item.repoId" :label="item.repoName"
                       :value="item.repoId" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="题型" align="center" prop="questionTypes">
        <template #default="scope">
          <el-select v-model="scope.row.questionTypes" placeholder="请选择" multiple
                     collapse-tags
                     collapse-tags-tooltip>
            <el-option v-if="scope.row.repoId"
                       v-for="(item,index) in repoList.find(item => item.repoId === scope.row.repoId).templateCount.questionTypeCount"
                       :key="index" :value="item.questionType" :label="QUESTION_TYPE_CONFIG[item.questionType].label">
              <a-flex justify="space-between">
                <span>{{ QUESTION_TYPE_CONFIG[item.questionType].label }}</span>
                <span>({{ item.count }})</span>
              </a-flex>
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tag">
        <template #default="scope">
          <el-select v-model="scope.row.tags" placeholder="请选择" multiple
                     collapse-tags
                     collapse-tags-tooltip>
            <el-option v-if="scope.row.repoId"
                       v-for="item in repoList.find(item => item.repoId === scope.row.repoId).templateCount.tagCount"
                       :label="item.tagName" :value="item.tagName">
              <a-flex justify="space-between">
                <span>{{ item.tagName }}</span>
                <span>({{ item.total }})</span>
              </a-flex>
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="题数" align="center" prop="questionNum">
        <template #default="scope">
          <el-input-number v-model="scope.row.num" :min="0" controls-position="right" />
        </template>
      </el-table-column>
      <el-table-column label="每题分数" align="center" prop="score">
        <template #default="scope">
          <el-input-number v-model="scope.row.score" :min="0" controls-position="right" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button plain icon="delete" type="danger" link @click="removeRow(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <a-empty />
      </template>
    </el-table>
    <a-button class="w-100%" type="dashed" @click="addRow()">
      <template #icon>
        <PlusOutlined />
      </template>
      添加一行数据
    </a-button>
    <div class="mt-3">
      <el-button plain type="success" :loading="loading" @click="submit">提交</el-button>
      <el-button @click="reset">重置</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.setting-nav {
  width: 84px;
  border-radius: 8px;
  padding: 12px 0;
  background: white;
}

.setting-nav-item {
  .nav-item-icon {
    margin-top: 8px;
    font-size: 24px;
  }

  span {
    font-size: 12px;
  }
}

.setting-content {
  flex: 1 1 70%;
  overflow-x: hidden;
  overflow-y: auto;
  max-width: 60%;
  margin: 0 auto;
}

.setting-card {
  padding-right: 14px;
  padding-left: 14px;
}

.setting-title {
  font-size: 18px;
}

.setting-item {
  padding: 15px 0;
  line-height: 32px;
  font-size: 16px;
  border-bottom: 1px solid #e1e7f2;
}

.setting-item-switch {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
<style lang="scss">
.setting-nav .el-anchor__marker {
  height: 28px !important;
}

.setting-nav .el-anchor__list {
  padding-left: 0 !important;
}
</style>
